package com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.view.View
import android.widget.ImageView
import androidx.core.content.FileProvider
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityVideoPlayerBinding
import com.gexiaobao.pigeon.permissions.PermissionInterceptor
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.dialog.RxDialogProgressBar
import com.gexiaobao.pigeon.viewmodel.ShedPigeonViewModel
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream

/**
 * @Author      : hxw
 * @Date        : 2024/6/13 14:05
 * @Describe    : 视频播放
 */
class ActivityVideoPlayer : BaseActivity<ShedPigeonViewModel, ActivityVideoPlayerBinding>() {

    private var mType = ""
    private var ringId: String = ""
    private var fosterName: String = ""
    private var passName: String = ""
    private var videoUrl = ""
    private var title = ""
    private var coverImage = ""
    private var videoPath = ""

    private var orientationUtils: OrientationUtils? = null
    private lateinit var dialogPro: RxDialogProgressBar

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        videoUrl = intent?.getStringExtra("videoUrl").toString()
        title = intent?.getStringExtra("title").toString()
        mType = intent.getStringExtra("type").toString()
        mDatabind.includeBar.tvTitle.text = title
        mDatabind.includeBar.tvRightMenu.isVisible = false
        mDatabind.includeBar.ivRightMenu.isVisible = true
        mDatabind.includeBar.tvRightMenu.text = "下载"

        mDatabind.videoPlayer.setUp(videoUrl, true, title)
        initVideoPlayer()

        mDatabind.videoPlayer.backButton.setOnClickListener {
            finish()
        }

        if (mType == "videoBackAndGather") {
            val featherColor = intent.getStringExtra("featherColor").toString()
            passName = intent.getStringExtra("passName").toString()
            fosterName = intent.getStringExtra("fosterName").toString()
            ringId = intent.getStringExtra("ringId").toString()
            coverImage = intent.getStringExtra("coverImage").toString()
            val showTime = intent.getStringExtra("showTime").toString()
            mDatabind.tvPassName.text = passName
            mDatabind.tvFosterName.text = fosterName
            mDatabind.tvRingId.text = ringId
            mDatabind.tvFeatherColor.text = featherColor
            mDatabind.tvShowTime.text = showTime
        }
        if (mType == "upload") {
            mDatabind.includeBar.toolBarLayout.isVisible = false
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.includeBar.ivBack, mDatabind.includeBar.tvRightMenu, mDatabind.includeBar.ivRightMenu) {
            when (it) {
                mDatabind.includeBar.ivRightMenu -> requestPermission()
                mDatabind.includeBar.ivBack -> finish()
                mDatabind.includeBar.tvRightMenu -> requestPermission()
            }
        }
    }

    private fun requestPermission() {
        XXPermissions.with(this@ActivityVideoPlayer)
            .permission(Permission.MANAGE_EXTERNAL_STORAGE)
            .interceptor(PermissionInterceptor())
            .request { _, allGranted ->
                if (allGranted) {
                    startDownload()
                } else {
                    showMessage("权限不足，请到设置中手动开启权限")
                }
            }
    }

    private fun startDownload() {
        /** 在生命周期感知的作用域中启动协程 */
        lifecycleScope.launch {
            try {
                downloadVideo()
                RxToast.success("视频下载完成")
                if (::dialogPro.isInitialized) dialogPro.dismiss()
                showIsShareToWeChatDialog()
            } catch (e: Exception) {
                RxToast.error("下载失败")
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun showIsShareToWeChatDialog() {
        val dialog = RxDialogDefault(this)
        dialog.setTitle("是否分享到微信?")
        dialog.setSureListener {
            val wxApi = WXAPIFactory.createWXAPI(this, Constant.WX_APP_ID)
            // 检查手机或者模拟器是否安装了微信
            if (!wxApi.isWXAppInstalled) {
                showMessage("未安装微信，请安装后进行分享")
                dialog.dismiss()
                return@setSureListener
            }
            dialog.dismiss()
            shareVideoLocal()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun shareVideoLocal() {
        val mDesc = "$ringId\n$passName-$fosterName"
        val videoUri: Uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 对于 Android 7.0 及以上版本，使用 FileProvider
            FileProvider.getUriForFile(this, this.packageName + ".provider", File(videoPath))
        } else {
            // 对于低版本 Android，可以直接使用 Uri.fromFile
            Uri.fromFile(File(videoPath))
        }
        val shareIntent = Intent(Intent.ACTION_SEND).apply {
            type = "video/mp4"  // 设置 MIME 类型
            putExtra(Intent.EXTRA_STREAM, videoUri)  // 将文件的 Uri 添加到 Intent 中
            putExtra(Intent.EXTRA_TEXT, mDesc)  // 附加文本描述
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)  // 允许临时读取权限
            setPackage("com.tencent.mm")  // 设置目标应用包名，确保是微信
        }
        startActivity(Intent.createChooser(shareIntent, "分享视频"))
    }

    private suspend fun downloadVideo() {
        showProgressBarDialog()
        // 在IO线程进行网络请求和文件写入
        withContext(Dispatchers.IO) {
            val client = OkHttpClient()
            val request = Request.Builder()
                .url(videoUrl)
                .build()
            try {
                val response: Response = client.newCall(request).execute()
                if (response.isSuccessful) {
                    val inputStream: InputStream = response.body?.byteStream() ?: throw IOException("响应体为空")

                    /** 获取外部存储路径 */
                    val videoDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), "PigeonVideos")
                    if (!videoDir.exists()) {
                        videoDir.mkdirs()
                    }
                    val videoFile = File(videoDir, "$ringId.mp4")

                    /** 创建文件输出流 */
                    val outputStream: OutputStream = FileOutputStream(videoFile)
                    val buffer = ByteArray(1024)
                    var bytesRead: Int
                    var totalBytesRead: Long = 0
                    val fileSize = response.body?.contentLength() ?: 0
                    /** 将文件写入存储 */
                    while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                        totalBytesRead += bytesRead.toLong()
                        outputStream.write(buffer, 0, bytesRead)

                        /** 计算下载进度 */
                        val progress = (totalBytesRead * 100 / fileSize).toInt()
                        withContext(Dispatchers.Main) {
                            /** 通知媒体扫描器，更新文件到媒体库 */
                            if (::dialogPro.isInitialized) {
                                dialogPro.setProgressInt(progress)
                            }
                        }
                    }
                    outputStream.close()
                    inputStream.close()
                    /** 通知媒体扫描器，更新文件到媒体库 */
                    withContext(Dispatchers.Main) {
                        MediaScannerConnection.scanFile(this@ActivityVideoPlayer, arrayOf(videoFile.absolutePath), null) { path, uri ->
                            // 这里可以做一些回调处理，例如日志记录
                            LogUtils.debugInfo("FileScan", "File scanned: $path -> $uri")
                        }
                    }
                    videoPath = videoFile.absolutePath
                    LogUtils.warnInfo(videoPath)
                } else {
                    LogUtils.warnInfo("Download", "下载失败")
                    if (::dialogPro.isInitialized) dialogPro.dismiss()
                }
            } catch (e: IOException) {
                e.printStackTrace()
                throw e
            }
        }
    }

    private fun showProgressBarDialog() {
        dialogPro = RxDialogProgressBar(this)
        dialogPro.setFullScreenWidth()
        dialogPro.setCanceledOnTouchOutside(false)
        dialogPro.show()
    }

    private fun initVideoPlayer() {
        //增加封面
        val imageView = ImageView(this)
        imageView.scaleType = ImageView.ScaleType.CENTER_CROP
        imageView.setImageResource(R.mipmap.app_icon_)
        mDatabind.videoPlayer.thumbImageView = imageView
        //增加title
        mDatabind.videoPlayer.titleTextView.visibility = if (mType == "auctionPigeon") View.GONE else View.VISIBLE
        //设置返回键
        mDatabind.videoPlayer.backButton.visibility =if (mType == "auctionPigeon") View.GONE else View.VISIBLE
        //设置旋转
        orientationUtils = OrientationUtils(this, mDatabind.videoPlayer)
        //设置全屏按键功能,这是使用的是选择屏幕，而不是全屏
        mDatabind.videoPlayer.fullscreenButton.setOnClickListener { // ------- ！！！如果不需要旋转屏幕，可以不调用！！！-------
            // 不需要屏幕旋转，还需要设置 setNeedOrientationUtils(false)
            //orientationUtils.resolveByClick();
            finish()
        }
        //是否可以滑动调整
        mDatabind.videoPlayer.setIsTouchWiget(true)
        //设置返回按键功能
        mDatabind.videoPlayer.backButton.setOnClickListener { }
        ///不需要屏幕旋转
        mDatabind.videoPlayer.isNeedOrientationUtils = false

        mDatabind.videoPlayer.startPlayLogic()
    }

    override fun onPause() {
        super.onPause()
        mDatabind.videoPlayer.onVideoPause()
    }

    override fun onResume() {
        super.onResume()
        mDatabind.videoPlayer.onVideoResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
        if (orientationUtils != null) orientationUtils!!.releaseListener()
    }
}